package online.inote.naruto.utils.http;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import online.inote.naruto.utils.log.LoggerFactory;
import online.inote.naruto.utils.time.Timer;

import java.io.IOException;

/**
 * @description 日志
 * @author gaopengsui@creditease.cn
 * @date 2021/06/01 14:04
 */
public class LogInterceptor implements Interceptor {

  private static final String POST_METHOD = "POST";
  private final LoggerFactory log = LoggerFactory.getLogger(getClass()).module("OK-HTTP-3");

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    log.info().message("request:[ {} ]").args(request.toString()).print();

    if (POST_METHOD.equals(request.method())) {
      log.info().message("request-headers:[ {} ]").args(request.headers().toString()).print();
      RequestBody requestBody = request.body();
      Buffer buffer = new Buffer();
      requestBody.writeTo(buffer);

      log.info()
          .message("request-contentType:[ {} ]")
          .args(requestBody.contentType().toString())
          .print();

      log.info().message("request-body:[ {} ]").args(buffer.readByteString().utf8()).print();
    }

    Timer timer = Timer.builder().build();
    Response response = chain.proceed(request);

    // 打印请求耗时
    log.info().message(timer.costTipMessage()).print();
    log.info().message("response-code:[ {} ]").args(response.code()).print();

    return response;
  }
}
